package org.jim.server.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImSessionContext;
import org.jim.core.packets.cs.chat.command.CsChatReqCmd;
import org.jim.core.packets.im.chat.command.ChatReqCmd;
import org.jim.core.packets.pub.pojo.JimUser;
import org.jim.core.session.id.impl.UUIDSessionIdGenerator;
import org.jim.core.utils.JsonKit;

/**
 * @FileName:
 * @Description:
 * @Author linjie
 * @Date 2020/8/245:38 PM
 * @Version 4.0.0
 */
@Slf4j
public class CsChatKit extends ChatKit{
    /**
     * 转换为聊天消息结构;
     * @param body
     * @param imChannelContext
     * @return
     */
    public static CsChatReqCmd toChatBody(byte[] body, ImChannelContext imChannelContext){
        CsChatReqCmd chatReqBody = parseChatBody(body);
        if(chatReqBody != null){
            if(StringUtils.isEmpty(chatReqBody.getFrom())){
                ImSessionContext imSessionContext = imChannelContext.getSessionContext();
                JimUser user = imSessionContext.getImClientNode().getUser();
                if(user != null){
                    chatReqBody.setFrom(user.getNick());
                }else{
                    chatReqBody.setFrom(imChannelContext.getId());
                }
            }
        }
        return chatReqBody;
    }

    /**
     * 判断是否属于指定格式聊天消息;
     * @param body
     * @return
     */
    private static CsChatReqCmd parseChatBody(byte[] body){
        if(body == null) {
            return null;
        }
        CsChatReqCmd chatReqBody = null;
        try{
            String text = new String(body,ImConst.CHARSET);
            chatReqBody = JsonKit.toBean(text,CsChatReqCmd.class);
            if(chatReqBody != null){
                if(chatReqBody.getCreateTime() == null) {
                    chatReqBody.setCreateTime(System.currentTimeMillis());
                }
                if(StringUtils.isEmpty(chatReqBody.getId())){
                    chatReqBody.setId(UUIDSessionIdGenerator.instance.sessionId(null));
                }
                return chatReqBody;
            }
        }catch(Exception e){
            log.error(e.toString());
        }
        return chatReqBody;
    }

    /**
     * 判断是否属于指定格式聊天消息;
     * @param bodyStr
     * @return
     */
    public static CsChatReqCmd parseChatBody(String bodyStr){
        if(bodyStr == null) {
            return null;
        }
        try {
            return parseChatBody(bodyStr.getBytes(ImConst.CHARSET));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
